# cf/services.py
import requests
import json
from datetime import datetime, date, timedelta
from django.db import transaction
from .models import CFUser, Submission, DailyStats


class CFAnalyzer:
    """Codeforces用户提交记录分析器"""

    def __init__(self, cf_user):
        """初始化分析器

        Args:
            cf_user: CFUser对象
        """
        self.cf_user = cf_user
        self.username = cf_user.handle
        self.base_url = "https://codeforces.com/api/"

    def get_user_submissions(self, from_timestamp=None):
        """获取用户提交记录

        Args:
            from_timestamp: 从指定时间戳开始获取，None表示获取所有

        Returns:
            提交记录列表，如果获取失败则返回空列表
        """
        try:
            url = f"{self.base_url}user.status"
            params = {"handle": self.username}
            if from_timestamp:
                params["from"] = from_timestamp

            response = requests.get(url, params=params, timeout=10)
            response.raise_for_status()
            data = response.json()

            if data["status"] == "OK":
                print(f"成功获取用户 {self.username} 的 {len(data['result'])} 条提交记录")
                return data["result"]
            else:
                print(f"API返回错误: {data.get('comment', '未知错误')}")
                return []
        except requests.exceptions.RequestException as e:
            print(f"网络请求失败: {e}")
            return []

    def get_today_submissions(self):
        """获取今日的提交记录

        Returns:
            今日提交记录列表
        """
        all_submissions = self.get_user_submissions()
        today = date.today()

        today_submissions = []
        for submission in all_submissions:
            submit_time = datetime.fromtimestamp(submission["creationTimeSeconds"]).date()
            if submit_time == today:
                today_submissions.append(submission)

        print(f"用户 {self.username} 今日提交记录: {len(today_submissions)} 条")
        return today_submissions

    def save_submission_to_db(self, submission_data):
        """保存单条提交记录到数据库

        Args:
            submission_data: 单条提交记录字典

        Returns:
            Submission对象或None
        """
        try:
            # 提取问题信息
            problem = submission_data.get("problem", {})
            problem_name = problem.get("name", "")
            problem_index = problem.get("index", "")
            contest_id = problem.get("contestId", "")
            tags = json.dumps(problem.get("tags", []))

            # 创建或更新提交记录
            submission, created = Submission.objects.get_or_create(
                user=self.cf_user,
                submission_id=submission_data["id"],
                defaults={
                    "contest_id": contest_id,
                    "problem_index": problem_index,
                    "problem_name": problem_name,
                    "programming_language": submission_data.get("programmingLanguage", ""),
                    "verdict": submission_data.get("verdict", ""),
                    "creation_time": datetime.fromtimestamp(submission_data["creationTimeSeconds"]),
                    "submission_time": submission_data["creationTimeSeconds"],
                    "tags": tags
                }
            )

            if created:
                print(f"用户 {self.username} 新增提交记录: {problem_name}")
            else:
                print(f"用户 {self.username} 提交记录已存在: {problem_name}")

            return submission
        except Exception as e:
            print(f"保存用户 {self.username} 提交记录失败: {e}")
            return None

    def update_daily_stats(self, target_date=None):
        """更新每日统计数据

        Args:
            target_date: 目标日期，None表示今日

        Returns:
            DailyStats对象或None
        """
        try:
            if target_date is None:
                target_date = date.today()

            start_of_day = datetime.combine(target_date, datetime.min.time())
            end_of_day = datetime.combine(target_date, datetime.max.time())

            # 获取该日期的所有提交记录
            date_submissions = Submission.objects.filter(
                user=self.cf_user,
                creation_time__gte=start_of_day,
                creation_time__lte=end_of_day
            )

            # 计算各项统计数据
            total_submissions = date_submissions.count()
            accepted_submissions = date_submissions.filter(verdict="OK").count()

            # 获取独特问题（去重）
            unique_problems = set()
            problems_solved = set()  # 使用set来统计真正解决的问题（AC的题目）

            for submission in date_submissions:
                problem_id = f"{submission.contest_id}{submission.problem_index}"
                unique_problems.add(problem_id)
                if submission.verdict == "OK":
                    problems_solved.add(problem_id)

            # 创建或更新每日统计
            daily_stats, created = DailyStats.objects.update_or_create(
                user=self.cf_user,
                date=target_date,
                defaults={
                    "total_submissions": total_submissions,
                    "accepted_submissions": accepted_submissions,
                    "problems_solved": len(problems_solved),  # 实际解决的问题数
                    "unique_problems": json.dumps(list(unique_problems))
                }
            )

            action = "创建" if created else "更新"
            print(f"{action}用户 {self.username} 的 {target_date} 统计")
            return daily_stats

        except Exception as e:
            print(f"更新用户 {self.username} 的每日统计失败: {e}")
            return None

    def update_today_data(self):
        """更新今日数据的主方法

        Returns:
            dict: 包含更新结果的字典
        """
        try:
            # 获取今日提交记录
            today_submissions = self.get_today_submissions()

            # 保存提交记录到数据库
            saved_count = 0
            for submission in today_submissions:
                if self.save_submission_to_db(submission):
                    saved_count += 1

            # 更新今日统计
            daily_stats = self.update_daily_stats()

            return {
                "success": True,
                "username": self.username,
                "today_submissions_count": len(today_submissions),
                "saved_submissions_count": saved_count,
                "daily_stats_updated": daily_stats is not None,
                "date": date.today().strftime("%Y-%m-%d")
            }

        except Exception as e:
            print(f"更新用户 {self.username} 的今日数据失败: {e}")
            return {
                "success": False,
                "error": str(e),
                "username": self.username
            }

    def update_all_history_data(self):
        """更新用户的所有历史数据

        Returns:
            dict: 包含更新结果的字典
        """
        try:
            # 获取所有提交记录
            all_submissions = self.get_user_submissions()

            # 保存所有提交记录到数据库
            saved_count = 0
            for submission in all_submissions:
                if self.save_submission_to_db(submission):
                    saved_count += 1

            # 更新所有日期的统计
            self.update_all_daily_stats()

            return {
                "success": True,
                "username": self.username,
                "total_submissions_count": len(all_submissions),
                "saved_submissions_count": saved_count
            }

        except Exception as e:
            print(f"更新用户 {self.username} 的历史数据失败: {e}")
            return {
                "success": False,
                "error": str(e),
                "username": self.username
            }

    def update_all_daily_stats(self):
        """更新所有日期的统计数据"""
        try:
            # 获取所有有提交记录的日期
            submission_dates = Submission.objects.filter(
                user=self.cf_user
            ).dates('creation_time', 'day', order='ASC')

            for submission_date in submission_dates:
                self.update_daily_stats(submission_date)

            print(f"完成更新用户 {self.username} 的所有日期统计，共 {len(submission_dates)} 天")

        except Exception as e:
            print(f"更新用户 {self.username} 的所有日期统计失败: {e}")


def update_all_active_users():
    """更新所有活跃用户的数据"""
    active_users = CFUser.objects.filter(is_active=True)
    results = []

    for user in active_users:
        analyzer = CFAnalyzer(user)
        result = analyzer.update_today_data()
        results.append(result)

    return results


def update_user_history_data(user_id):
    """更新指定用户的历史数据"""
    try:
        user = CFUser.objects.get(id=user_id, is_active=True)
        analyzer = CFAnalyzer(user)
        result = analyzer.update_all_history_data()
        return result
    except CFUser.DoesNotExist:
        return {
            "success": False,
            "error": "用户不存在或未激活"
        }